﻿using System;
using System.Linq;
using System.Threading.Tasks;
using System.Transactions;
using WalkingTec.Mvvm.Core;
using HengTong.Model.Db.Hr.Bill;
using HengTong.Model.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using TiaoTaoHelper.Models;
using TiaoTaoHelper.Wtm.Interfaces;
using TiaoTaoHelper.Wtm.Models;
using UUIDNext;
using IFlow = TiaoTaoHelper.Wtm.Models.IFlow;


namespace HengTong.ViewModel.Hr.SysHrStaffNeedRequestBillVms
{
    public partial class SysHrStaffNeedRequestBillVm : CrudVm<SysHrStaffNeedRequestBill>
    {
        public SysHrStaffNeedRequestBillVm()
        {
            SetInclude(x => x.StaffNeedSubs);
            SetInclude(x => x.Org);
            SetInclude(x => x.Group);
        }

        protected override void InitVM()
        {
            base.InitVM();
        }

        public override async Task DoAddAsync()
        {
            // 校验部门与公司的关系
            if (Entity.GroupId.HasValue && Entity.OrgId.HasValue)
            {
                var isValid = await ValidateGroupBelongsToOrgAsync(Entity.GroupId, Entity.OrgId);
                if (!isValid)
                {
                    MSD.AddModelError("GroupId", "所选部门不属于该公司，请重新选择");
                    return;
                }
            }

            if (Entity is IBill bill)
            {
                Entity.BillStatus = BillStatus.草稿;
                Entity.WorkflowStatus = WorkflowStatus.待提交;
                var result = await GenerateCodeAsync();
                if (result.Code == 200)
                {
                    Entity.BillCode = result.Data;
                }
                else
                {
                    MSD.AddModelError(" ", $"生成编码异常. {result.Message}");
                    return;
                }
            }

            Entity.ID = Uuid.NewDatabaseFriendly(Database.SqlServer);
            if (Entity is IBasePoco poco)
            {
                poco.CreateBy = Wtm.LoginUserInfo?.ITCode;
                poco.UpdateBy = Wtm.LoginUserInfo?.ITCode;
                poco.CreateTime = DateTime.Now;
                poco.UpdateTime = DateTime.Now;
            }

            await base.DoAddAsync();
        }


        /// <summary>
        /// 生成编码
        /// </summary>
        /// <returns></returns>
        public async Task<Result<string>> GenerateCodeAsync()
        {
            if (Entity is IBill bill)
            {
                var scope = Wtm.ServiceProvider.CreateScope();
                var service = scope.ServiceProvider.GetRequiredService<CodeGeneratorService>();
                var code = await service.GenerateCodeAsync(Entity.GetType().Name);
                return new Result<string>()
                {
                    Data = code
                };
            }

            return new Result<string>("实体未实现IBill接口");
        }

        /// <summary>
        /// 预测编码
        /// </summary>
        /// <returns></returns>
        public async Task<Result<string>> PredictCodeAsync()
        {
            if (Entity is IBill bill)
            {
                var scope = Wtm.ServiceProvider.CreateScope();
                var service = scope.ServiceProvider.GetRequiredService<CodeGeneratorService>();
                var code = await service.PreviewNextCodeAsync(Entity.GetType().Name);
                return new Result<string>()
                {
                    Data = code
                };
            }

            return new Result<string>("实体未实现IBill接口");
        }

        public override async Task DoEditAsync(bool updateAllFields = false)
        {
            // 校验部门与公司的关系
            if (Entity.GroupId.HasValue && Entity.OrgId.HasValue)
            {
                var isValid = await ValidateGroupBelongsToOrgAsync(Entity.GroupId, Entity.OrgId);
                if (!isValid)
                {
                    MSD.AddModelError("GroupId", "所选部门不属于该公司，请重新选择");
                    return;
                }
            }

            if (Entity is IBill { WorkflowStatus: WorkflowStatus.提交中 })
            {
                // 判断子表是否存在数据
                var entries = await DC.Set<SysHrStaffNeedRequestBillEntry>()
                    .Where(f => f.HrStaffNeedId == Entity.ID)
                    .AsNoTracking()
                    .ToListAsync();
                if (!entries.Any())
                {
                    MSD.AddModelError(" ", "请添加用人需求明细后再提交审核.");
                    return;
                }

                var raw = await DC.Set<SysHrStaffNeedRequestBill>()
                    .AsNoTracking()
                    .FirstOrDefaultAsync(e => e.ID == Entity.ID);
                if (raw.WorkflowStatus != WorkflowStatus.待提交)
                {
                    MSD.AddModelError(" ", "单据已提交审核,请勿重复提交.");
                    return;
                }

                var result = await StartWorkflowAsync("用人需求流程");
                if (result == null) return;
                if (!result.Executed)
                {
                    MSD.AddModelError(" ", $"提交审核异常. {result.Exception?.Message}");
                    return;
                }

                Entity.BillStatus = BillStatus.正文;
                Entity.WorkflowStatus = WorkflowStatus.审核中;
            }

            if (Entity is IBasePoco poco)
            {
                poco.UpdateBy = Wtm.LoginUserInfo?.ITCode;
                poco.UpdateTime = DateTime.Now;
            }

            await base.DoEditAsync(updateAllFields);
        }

        /// <summary>
        /// 必须使用异步事务, 否则工作流引擎会和当前事务冲突
        /// </summary>
        /// <param name="upAllFields"></param>
        public async Task ApproveAsync(bool upAllFields = false)
        {
            using var transactionScope = new TransactionScope(
                TransactionScopeOption.Required,
                new TransactionOptions
                {
                    IsolationLevel = IsolationLevel.ReadCommitted,
                    Timeout = TimeSpan.FromMinutes(10) // 增加超时时间到10分钟
                },
                TransactionScopeAsyncFlowOption.Enabled);
            try
            {
                if (Entity.BillStatus == BillStatus.草稿) Entity.BillStatus = BillStatus.正文;
                Entity.Approver = Wtm.LoginUserInfo?.ITCode;
                Entity.ApprovalTime = DateTime.Now;

                await base.DoEditAsync(upAllFields);
                if (MSD.IsValid)
                {
                    var result = await ContinueWorkflowAsync(ActionName, Remark, "用人需求流程");
                    if (result.Executed == true)
                    {
                        transactionScope.Complete(); // 提交事务
                    }
                    else
                    {
                        MSD.AddModelError(" ", $"工作流执行失败");
                    }
                }
                // 如果到这里，事务会自动回滚
            }
            catch (Exception e)
            {
                // TransactionScope会自动回滚，无需手动操作
                MSD.AddModelError(" ", $"审批操作异常: {e.Message}");
            }
        }

        public override void DoDelete()
        {
            base.DoDelete();
        }

        /// <summary>
        /// 校验部门是否属于指定公司
        /// </summary>
        /// <param name="groupId">部门ID</param>
        /// <param name="orgId">公司ID</param>
        /// <returns>校验结果</returns>
        private async Task<bool> ValidateGroupBelongsToOrgAsync(Guid? groupId, Guid? orgId)
        {
            if (!groupId.HasValue || !orgId.HasValue)
            {
                return false;
            }

            var exists = await DC.Set<SysGroup>()
                .Where(g => g.ID == groupId.Value)
                .Where(g => g.Organizations.Any(o => o.OrgId == orgId.Value))
                .AnyAsync();

            return exists;
        }
    }
}